package com.hu.bgp.server;

import java.io.File;

import org.apache.commons.vfs.FileChangeEvent;
import org.apache.commons.vfs.FileListener;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.impl.DefaultFileMonitor;

import com.hu.bgp.exceptions.BgpServerException;
import com.hu.bgp.util.ExtensionOnlyFilter;

public class BarFileSystemWatcher
{
	private DefaultFileMonitor fsMonitor;
	private GameServerContext gsc;

	public BarFileSystemWatcher(GameServerContext gsc)
	{
		this.gsc = gsc;
		fsMonitor = new DefaultFileMonitor(new BarFileListener());
	}

	public void start()
	{
		loadInitialFiles();
		try
		{
			FileSystemManager fsManager = VFS.getManager();
			FileObject listendir = fsManager.resolveFile(gsc.getConfiguration().getBarRootPath());
			fsMonitor.addFile(listendir);
			fsMonitor.start();
		}
		catch (FileSystemException e)
		{
			throw new BgpServerException("Error setting the bar source directory. check BGP config!", e);
		}
	}

	private void loadInitialFiles()
	{
		File barRootDir = new File(gsc.getConfiguration().getBarRootPath());
		if (!barRootDir.exists())
		{
			throw new BgpServerException("Invalid bar dir: " + barRootDir + " does not exist. Check BGP Configuration");
		}
		for (File barArchive : barRootDir.listFiles(new ExtensionOnlyFilter(".jar")))
		{
			try
			{
				gsc.getBarLoader().load(barArchive);
			}
			catch (BgpServerException e)
			{
				System.out.println("BarFileSystemWatcher.loadInitialFiles: Could not load a bar file, so I am skipping it.");
				e.printStackTrace();
			}
		}
	}

	public void stop()
	{
		fsMonitor.stop();
	}

	private static boolean isValidExtension(String extension)
	{
		return extension.equals("jar");
	}

	private class BarFileListener implements FileListener
	{
		public void fileChanged(FileChangeEvent fce) throws Exception
		{
		}

		public void fileCreated(FileChangeEvent fce) throws Exception
		{
			System.out.println("BarFileSystemWatcher.BarFileListener.fileCreated: " + fce.getFile().getName());
			if (isValidExtension(fce.getFile().getName().getExtension()))
			{
				File barArchive = new File(fce.getFile().getName().getPath());
				try
				{
					gsc.getBarLoader().load(barArchive);
				}
				catch (BgpServerException e)
				{
					System.out.println("BarFileSystemWatcher.BarFileListener.fileCreated: could not load a bar file, so I am skipping it.");
					e.printStackTrace();
				}
			}
		}

		public void fileDeleted(FileChangeEvent fce) throws Exception
		{
		}
	}
}
